<?php

namespace app\dlc\controller;

use think\Controller;
use think\Model;
use think\Db;
use think\Config;
use think\Request;
use think\View;
use think\Session;

class BaseController extends Controller
{
    protected static $SYS; //系统级全局静态变量
    protected static $CMS; //CMS全局静态变量
    protected static $SHOP; //Shop变量全局设置
	protected static $REQUEST; //Shop变量全局设置
    protected $shop_id=0;
    protected $agent_id=0;
    protected $uid;
    protected $role_id;
    protected $token;
    protected $publicUrl = PROJECT_URL;
    protected $map = [];//初始化一些需要判断的条件
    protected $parameter = [];//分页的时候需要传递的变量数组
    static $p,$psize;
    static $page;

    //初始化验证模块
    protected function _initialize()
    {
        //预留检测
		parent::_initialize();
		self::$REQUEST = Request::instance();
		if (input('p') || input('page')){
            self::$p = input('p')+input('page');
        }else{
            self::$p=1;
        }
        self::$psize = input('psize')?:20;
        self::$page = self::$p . ',' . self::$psize;
        //刷新系统全局配置
        self::$SYS['set'] = $_SESSION['SYS']['set'] = $this->checkSysSet();
		$request = Request::instance();
        //检测登陆状态
        $check = $this->checkLogin();
        $action =  $request->action();
        $other = array('login','logout','reg','verify');
        if(!in_array($action, $other)){
           $this ->uid = Session::get('CMS.uid');//必须保证有Userid，去掉登录功能模块↑
           $this ->user = Session::get('CMS.user');//必须保证有Userid，去掉登录功能模块↑
           $role_id = Db::name('admin') -> where(array('id' => $this ->uid))->value('roleid');
           $this->role_id = $role_id;
           $auth = Db::table('dlc_role') -> where(array('role_id' => $role_id))->value('auth');
           if (empty($auth)){
               echo '无可查看的菜单';
               die;
           }
           $role_oath = Db::table('dlc_role_oath') ->where("oath_id in (".$auth.")")->column('url','oath_id');
           foreach ($role_oath as $k => $v) {
                if($v) {
                    if(strpos($v,"?")) {
                        $role_oath[$k] = explode("?", $v)[0];
                    }
                }
            }
            $this->auth = $role_oath;
        }
        $this->assign('uid',$this->uid);
        if ($this->uid!=1){//非主管理员登录
        $res = model('shop')->where('aid',$this->uid)->value('shop_id');
        if ($res){
            $this->shop_id = $res;
            $this->assign('shop_id',$this->shop_id);
            $this->map['shop_id'] = $this->shop_id;
        }
        $res = Db::name('agent')->where('aid',$this->uid )->value('agent_id');
        if ($res){
            $this->agent_id = $res;
            $this->assign('agent_id',$this->agent_id);
            $this->map['agent_id'] = $this->agent_id;
        }
        }{
        if (input('shop_id')) {
            $this->map['shop_id'] = input('shop_id');
            $this->assign('shop_id',$this->shop_id);
        };
        if (input('agent_id')){
            $this->map['agent_id'] = input('agent_id');
            $this->assign('agent_id',$this->agent_id);
            };
        }

        $request= Request::instance();
        $module_name=$request->module();
        $controller_name=$request->controller();
        $action=$request->action();
        $active_url=$module_name.'/'.$controller_name.'/'.$action;
        $this->assign('self_url',$active_url);//获取当前的url，替换搜索位置的url
    }

    //返回系统全局配置
    public function checkSysSet()
    {
        $set = model('Set')->find();
        return $set ? $set : utf8error('系统还未配置！');
    }

    //检查用户是否登陆,返回TRUE或跳转登陆
    public function checkLogin()
    {
        $passlist = array('login', 'logout', 'reg', 'verify'); //不检测登陆状态的操作
		$request = Request::instance();
		$action =  $request->action();
        $check = in_array($action, $passlist);
        if (!$check) {
            if (!Session::has('CMS.uid')) {
                $this->redirect('Dlc/Public/login');
            }
        } else {
            return true;
        }
    }

    //拼装面包导航
    public function getBread($bread)
    {
        if ($bread) {
            $this->assign('bread', $bread);
            return $this->fetch('common/Base_bread');
        } else {
            $this->error('请传入面包导航！');
        }
    }


    //获取单张图片
    public function getPic($id)
    {
        $m = model('Upload');
        $map['id'] = $id;
        $list = $m->where($map)->find();
        if ($list) {
            $list['imgurl'] = PROJECT_URL . '/public' . $list['savepath'] . $list['savename'];
        }
        return $list['imgurl'] ? $list['imgurl'] : "";
    }

    //获取图集合
    public function getAlbum($ids)
    {
        $m = model('Upload');
        $map['id'] = array('in', parse_str($ids));
        $list = $m->where($map)->select();
        foreach ($list as $k => $v) {
            $list[$k]['imgurl'] = "/Upload/" . $list[$k]['savepath'] . $list[$k]['savename'];
        }
        return $list ? $list : "";
    }

    //获取图集合
    public function getAlbum1($ids)
    {
        $m = model('Upload');
        $map['id'] = array('in', parse_str($ids));
        $list = $m->where($map)->select();
        foreach ($list as $k => $v) {
            $list[$k][] = "/Upload/" . $list[$k]['savepath'] . $list[$k]['savename'];
        }
        return $list ? $list : "";
    }

    //获取会员等级经验对称数据
    public function getlevel($exp)
    {
        $data = model('Vip_level')->order('exp')->select();
        if ($data) {
            $level = array();
            foreach ($data as $k => $v) {
                if ($k + 1 == count($data)) {
                    if ($exp >= $data[$k]['exp']) {
                        $level['levelid'] = $data[$k]['id'];
                        $level['levelname'] = $data[$k]['name'];
                    }
                } else {
                    if ($exp >= $data[$k]['exp'] && $exp < $data[$k + 1]['exp']) {
                        $level['levelid'] = $data[$k]['id'];
                        $level['levelname'] = $data[$k]['name'];
                    }
                }
            }
        } else {
            return utf8error('会员等级未定义！');
        }
        return $level;
    }

    public function info_return($status,$msg){
        $data['status'] = $status;
        $data['msg'] = $msg;
        return $data;

    }

	/**
	 * 封装分页类
	 * @param $count 操作URL
	 * @param $psize 记录信息
	 * @param $loader 模块
	 * @param $loadername 模块名
	 * @param $searchname 搜索
	 * @param $map
	 */
	public function getPage($count, $psize, $loader, $loadername, $searchname){
		if (!$count && !$psize || !$loader || !$loadername) {
		        dump($count);
		        dump($psize);
		        dump($loader);
		        dump($loadername);
		        dump($searchname);
				die('缺少分页参数!');
		}
       		$parameter = $_GET+$this->parameter;
		$page = new \pagecms\pagecms($count, $psize,$parameter); // 实例化分页类 传入总记录数和每页显示的记录数
		$page->setConfig('loader', $loader);
		$page->setConfig('loadername', $loadername);
		//绑定前端form搜索表单ID,默认为#App-search
		if ($searchname) {
			 $page->setConfig('searchname', $searchname);
		}
		$show = $page->show(); // 分页显示输出
		$this->assign('page', $show);
		return true;
	}

     /**
     * 手机号正则判断 正确返回false，错误返回true
     * [check_mobile description]
     * @param  [type] $phone [description] 手机号
     * @return [type]        [description]
     */
    protected function check_mobile($phone){
        if(preg_match("/^1[34578]\d{9}$/", $phone)){
            return false;
        }
        return true;
    }

    public function mergeBread($array) { //by Lar
        if(!$array) return false;
        $bread = [];
        foreach ($array as $k => $v) {
            $bread[] = ['name' => $v];
        }
        $this->assign('breadhtml',$this->getBread($bread));
    }



    public function bread_ini($data){
        if (!is_array($data)){
            $res1 = explode(',',$data);
            $res2 = explode('-',$data);
            $data = count($res1)>count($res2)?$res1:$res2;

        }
        $bread = [];
        foreach ($data as $key=>$value){
            $bread[$key]['name'] = $value;
        }
        $this->assign('breadhtml', $this->getBread($bread));
    }

    function array_column(array $array, $column_key, $index_key=null){
        $result = [];
        foreach($array as $arr) {
            if(!is_array($arr)) continue;

            if(is_null($column_key)){
                $value = $arr;
            }else{
                $value = $arr[$column_key];
            }

            if(!is_null($index_key)){
                $key = $arr[$index_key];
                $result[$key] = $value;
            }else{
                $result[] = $value;
            }
        }
        return $result;
    }
    /**
     * curl POST
     *
     * @param   string  url
     * @param   array   数据
     * @param   int     请求超时时间
     * @param   bool    HTTPS时是否进行严格认证
     * @return  string
     */
    function curlPost($url, $data = array(), $timeout = 30, $CA = false){

        $cacert = getcwd() . '/cacert.pem'; //CA根证书
        $SSL = substr($url, 0, 8) == "https://" ? true : false;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout-2);
        if ($SSL && $CA) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);   // 只信任CA颁布的证书
            curl_setopt($ch, CURLOPT_CAINFO, $cacert); // CA根证书（用来验证的网站证书是否是CA颁布）
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名，并且是否与提供的主机名匹配
        } else if ($SSL && !$CA) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); //避免data数据过长问题
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //data with URLEncode

        $ret = curl_exec($ch);
        //var_dump(curl_error($ch));  //查看报错信息

        curl_close($ch);
        return $ret;
    }
    //检测url是否存在
    function url_exists($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($ch); // $resp = curl_exec($ch);
        $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
//        如果对于302这样的跳转也算作访问成功的话，你也可以加入到判断里面。
        if ($curl_code == 200 || $curl_code == 302) {
            return true;
            echo '连接成功，状态码：' . $curl_code;
        } else {
            return false;
            echo '连接失败，状态码：' . $curl_code;
        }
    }



    function curl_post($url,$param){
        $ch = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        // 配置
        curl_setopt($ch,CURLOPT_URL,$url);
        //增加配置，不让结果默认显示，并且可以接收
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//0是默认值，默认把数据展示   1 不展示数据，可以接收   RETURN返回   TRANSFER转义、运输
        //添加配置，告诉curl我要用POST方式请求，因为curl发送请求的方式默认是get
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$param);//设置POST需要传递的值
        //执行
        $result = curl_exec($ch);
        $aStatus = curl_getinfo($ch);
        curl_close($ch);
        if (intval($aStatus["http_code"]) == 200) {
            return $result;
        } else {
            return false;
        }
    }
}
?>
